package org.liveboardgames.agricola.business;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.liveboardgames.agricola.access.IGameDao;
import org.liveboardgames.agricola.business.helper.GameHelper;
import org.liveboardgames.agricola.business.updater.GameUpdater;
import org.liveboardgames.agricola.business.updater.IResourceUpdater;
import org.liveboardgames.agricola.controller.AgricolaUpdateAdapter;
import org.liveboardgames.agricola.domain.Change;
import org.liveboardgames.agricola.domain.Game;
import org.liveboardgames.agricola.domain.common.IResourceContainer;

public class ResourceServiceImpl implements IResourceService {

  private IGameDao gameDao;

  public void setGameDao(IGameDao gameDao) {
    this.gameDao = gameDao;
  }

  public void addResource(Long gameId, Long targetId, String targetType, Map<String, Integer> resources) {
    Game game = gameDao.load(gameId);

    List<Change> changes = new ArrayList<Change>();

    IResourceContainer host = new GameHelper().findResourceContainer(game, targetId, targetType);
    IResourceUpdater updater = new UpdaterFactory().getResourceUpdater(changes, host);
    updater.addResources(resources);

    // TODO: this works as long as it is only used as an action...
    GameUpdater gameUpdater = new GameUpdater(game, changes);
    gameUpdater.setHasPlayerPlayedPeep(true);

    gameDao.save(game);

    new AgricolaUpdateAdapter().publishGameUpdates(gameId, changes);
  }

  public void removeResource(Long gameId, Long targetId, String targetType, Map<String, Integer> resources) {
    Map<String, Integer> inversedResources = new HashMap<String, Integer>();
    for (String resourceType : resources.keySet()) {
      inversedResources.put(resourceType, -resources.get(resourceType));
    }

    addResource(gameId, targetId, targetType, inversedResources);
  }

}
